package com.xh.bussiness.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.course.bean.request.PrepareConfigGroupRequest;
import com.xh.bussiness.course.model.Course;
import com.xh.bussiness.course.model.PrepareConfigGroup;
import com.xh.bussiness.course.dao.PrepareConfigGroupMapper;
import com.xh.bussiness.course.model.PrepareConfigGroupUser;
import com.xh.bussiness.course.model.PrepareUserConfig;
import com.xh.bussiness.course.service.ICourseService;
import com.xh.bussiness.course.service.IPrepareConfigGroupService;
import com.xh.bussiness.course.service.IPrepareConfigGroupUserService;
import com.xh.bussiness.permission.bean.dto.UserDto;
import com.xh.bussiness.permission.bean.request.QueryUserRequest;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.system.bean.request.GlobalPrepareConfigGroupRequest;
import com.xh.bussiness.system.model.GlobalPrepareConfigGroup;
import com.xh.bussiness.system.model.UserDataPermission;
import com.xh.bussiness.system.service.IGlobalPrepareConfigGroupService;
import com.xh.bussiness.system.service.IUserDataPermissionService;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.ObjectUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jqm
 * @since 2021-02-05
 */
@Service
public class PrepareConfigGroupServiceImpl extends BaseServiceImpl<PrepareConfigGroupMapper, PrepareConfigGroup> implements IPrepareConfigGroupService {

    @Autowired
    private IGlobalPrepareConfigGroupService globalPrepareConfigGroupService;
    @Autowired
    private IPrepareConfigGroupUserService prepareConfigGroupUserService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private IUserDataPermissionService userDataPermissionService;

    @Override
    public XhPage queryPrepareConfigGroupPage(XhPage page, PrepareConfigGroupRequest bean) {
        QueryWrapper qw = new QueryWrapper<PrepareConfigGroup>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page, qw);
    }

    @Override
    public List<PrepareConfigGroup> queryPrepareConfigGroup(PrepareConfigGroupRequest bean) {
        QueryWrapper qw = new QueryWrapper<PrepareConfigGroup>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return this.dao.selectList(qw);
    }

    @Override
    public String createDefaultGroups(String courseId) {
        // 先判断该课程有没有分组，如果有则不初始化
        QueryWrapper<PrepareConfigGroup> qw = new QueryWrapper();
        qw.eq("course_id", courseId);
        List<PrepareConfigGroup> prepareConfigGroups = super.queryByCondition(qw);
        if (!CollectionUtils.isEmpty(prepareConfigGroups)) {
            return "成功了";
        }

//        GlobalPrepareConfigGroupRequest bean = new GlobalPrepareConfigGroupRequest();
//        bean.setDefaulted(1);
//        List<GlobalPrepareConfigGroup> globalPrepareConfigGroups = globalPrepareConfigGroupService.queryGlobalPrepareConfigGroup(bean);
//        for (GlobalPrepareConfigGroup globalPrepareConfigGroup : globalPrepareConfigGroups) {
//            PrepareConfigGroup prepareConfigGroup = new PrepareConfigGroup();
//            prepareConfigGroup.setCourseId(courseId);
//            ObjectUtils.copyNonNullProperties(globalPrepareConfigGroup,prepareConfigGroup);
//            super.insert(prepareConfigGroup);
//        }

        // 手动添加无权限组，因为全局设置里不需要无权限组
        PrepareConfigGroup directTeachingGroup = new PrepareConfigGroup();
        directTeachingGroup.setCourseId(courseId);
        directTeachingGroup.setName("直接上课组");
        directTeachingGroup.setConfig("{\"teachPlan\":0,\"reviewVideo\":0,\"directTeaching\":1,hasPermission:1}");
        super.insert(directTeachingGroup);

        // 手动添加无权限组，因为全局设置里不需要无权限组
        PrepareConfigGroup noPerssionGroup = new PrepareConfigGroup();
        noPerssionGroup.setCourseId(courseId);
        noPerssionGroup.setName("无权限组");
        noPerssionGroup.setConfig("{\"teachPlan\":0,\"reviewVideo\":0,\"directTeaching\":0,hasPermission:0}");
        super.insert(noPerssionGroup);
        return "成功了";
    }

    @Override
    public String addUsers(PrepareConfigGroupRequest bean) {
        // 先删除原先的数据
        QueryWrapper<PrepareConfigGroupUser> qw = new QueryWrapper();
        qw.eq("group_id", bean.getGroupId());
        prepareConfigGroupUserService.deleteByCondition(qw);
        if (CollectionUtils.isEmpty(bean.getUserIds())) {
            return null;
        }
//        PrepareConfigGroup prepareConfigGroup = super.getById(bean.getGroupId());
        for (String userId : bean.getUserIds()) {
            // 删除用户原先所在分组
            QueryWrapper<PrepareConfigGroupUser> userQueryWrapper = new QueryWrapper();
            userQueryWrapper.eq("user_id", userId);
            prepareConfigGroupUserService.deleteByCondition(userQueryWrapper);

            PrepareConfigGroupUser prepareConfigGroupUser = new PrepareConfigGroupUser();
            prepareConfigGroupUser.setGroupId(bean.getGroupId());
            prepareConfigGroupUser.setUserId(userId);
            prepareConfigGroupUser.setCourseId(bean.getCourseId());
            prepareConfigGroupUserService.insert(prepareConfigGroupUser);
        }
        PrepareConfigGroup prepareConfigGroup = new PrepareConfigGroup();
        prepareConfigGroup.setId(bean.getGroupId());
        prepareConfigGroup.setUserCount(bean.getUserIds().size());
        super.update(prepareConfigGroup);
        return null;
    }

    @Override
    public XhPage<Map<String, Object>> queryUsersByGroupId(XhPage page, String courseId, String groupId, String userName) {
        // 默认组，查询所有没有分组的教师，要根据教师的权限查询（学科、班型）
        List<String> userIds = new ArrayList<>();
        if ("0".equals(groupId)) {
            // 先查询处该课程拥有的学科、班型
            Course course = courseService.getById(courseId);
            String subject = course.getSubjectId();
            String courseTypeId = course.getCourseTypeId();
            QueryWrapper<UserDataPermission> qw = new QueryWrapper<>();
            qw.eq("subject_code",subject);
            qw.like("course_type_id",courseTypeId);
            if(StringUtils.isNotEmpty(course.getYear())){
                qw.like("year",course.getYear());
            }
            if(StringUtils.isNotEmpty(course.getSemesterId())){
                qw.like("term_id",course.getSemesterId());
            }
            if(StringUtils.isNotEmpty(course.getGradeId())){
                qw.like("grade_id",course.getGradeId());
            }
            List<UserDataPermission> list = userDataPermissionService.queryByCondition(qw);
            if(CollectionUtils.isEmpty(list)){
                page.setRecords(new ArrayList());
                return page;
            }
            userIds = list.stream().map(UserDataPermission ::getUserId).collect(Collectors.toList());
//            // 去掉其他组的用户
            QueryWrapper groupUserQw = new QueryWrapper<>();
            groupUserQw.eq("course_id", courseId);
            List<PrepareConfigGroupUser> groupUsers = prepareConfigGroupUserService.queryByCondition(groupUserQw);
            if(!CollectionUtils.isEmpty(groupUsers)){
                List<String> otherUserIds = groupUsers.stream().map(PrepareConfigGroupUser :: getUserId).collect(Collectors.toList());
                userIds.removeAll(otherUserIds);
            }
        } else {
            QueryWrapper<PrepareConfigGroupUser> qw = new QueryWrapper<>();
            qw.eq("group_id",groupId);
            List<PrepareConfigGroupUser> list = prepareConfigGroupUserService.queryByCondition(qw);
            userIds = list.stream().map(PrepareConfigGroupUser :: getUserId).collect(Collectors.toList());
        }
        if(userIds.size() ==0){
            page.setRecords(new ArrayList());
            return page;
        }
        QueryUserRequest bean = new QueryUserRequest();
        bean.setUserIds(userIds);
        if(StringUtils.isNotEmpty(userName)){
            bean.setUsername(userName);
        }
        return userService.queryUserPage(page, bean);
    }

    @Override
    public XhPage<Map<String, Object>> queryUsers(XhPage page, String courseId, String userName) {
        // 默认组，查询所有没有分组的教师，要根据教师的权限查询（学科、班型）
        List<String> userIds = new ArrayList<>();
        // 先查询处该课程拥有的学科、班型
        Course course = courseService.getById(courseId);
        String subject = course.getSubjectId();
        String courseTypeId = course.getCourseTypeId();
        QueryWrapper<UserDataPermission> dataPermissionQueryWrapper = new QueryWrapper<>();
        dataPermissionQueryWrapper.eq("subject_code",subject);
        dataPermissionQueryWrapper.like("course_type_id",courseTypeId);
        if(StringUtils.isNotEmpty(course.getYear())){
            dataPermissionQueryWrapper.like("year",course.getYear());
        }
        if(StringUtils.isNotEmpty(course.getSemesterId())){
            dataPermissionQueryWrapper.like("term_id",course.getSemesterId());
        }
        if(StringUtils.isNotEmpty(course.getGradeId())){
            dataPermissionQueryWrapper.like("grade_id",course.getGradeId());
        }
        List<UserDataPermission> dataPermissions = userDataPermissionService.queryByCondition(dataPermissionQueryWrapper);
        if(CollectionUtils.isEmpty(dataPermissions)){
            page.setRecords(new ArrayList());
            return page;
        }
        userIds = dataPermissions.stream().map(UserDataPermission ::getUserId).collect(Collectors.toList());
        QueryUserRequest bean = new QueryUserRequest();
        bean.setUserIds(userIds);
        if(StringUtils.isNotEmpty(userName)){
            bean.setUsername(userName);
        }
        page = userService.queryUserPage(page, bean);

        // 根据用户id查询所有组id
        QueryWrapper<PrepareConfigGroupUser> groupUserQueryWrapper = new QueryWrapper<>();
        groupUserQueryWrapper.in("user_id",userIds);
        List<PrepareConfigGroupUser> groupUsers = prepareConfigGroupUserService.queryByCondition(groupUserQueryWrapper);
        List<String> gourpIds = groupUsers.stream().map(PrepareConfigGroupUser :: getGroupId).collect(Collectors.toList());

        // 根据组id查询处所有组
        QueryWrapper<PrepareConfigGroup> qw = new QueryWrapper<>();
        qw.in("id", gourpIds);
        List<PrepareConfigGroup> groups = super.queryByCondition(qw);
        List<Map<String, Object>> list = page.getRecords();

        // 设置用户的组名称
        for (Map<String, Object> map : list) {
            String userId = MapUtils.getString(map, "id");
            for (PrepareConfigGroupUser groupUser : groupUsers) {
                if(groupUser.getUserId().equals(userId)){
                    for (PrepareConfigGroup group : groups) {
                        if(groupUser.getGroupId().equals(group.getId())){
                            map.put("groupName",group.getName());
                        }
                        break;
                    }
                    break;
                }
            }
            // 没有组的为默认组
            if (map.get("groupName") == null) {
                map.put("groupName","默认组");
            }
        }
        return page;
    }

    @Override
    public String getUserPrepareConfig(String userId, String courseId) {
        PrepareConfigGroup prepareConfigGroup = super.dao.queryByUserIdAndCourseId(userId, courseId);
        // 先查询课程备课设置
        if(prepareConfigGroup != null){
            return prepareConfigGroup.getConfig();
        }
        // 再查询全局备课设置
        GlobalPrepareConfigGroup globalPrepareConfigGroup = globalPrepareConfigGroupService.queryByUserId(userId);
        if(globalPrepareConfigGroup != null){
            return globalPrepareConfigGroup.getConfig();
        }
        // 默认配置
        globalPrepareConfigGroup = globalPrepareConfigGroupService.getById("0");
        return globalPrepareConfigGroup.getConfig();
    }

    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(PrepareConfigGroupRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (StringUtils.isNotEmpty(bean.getCourseId())) {
            qw.eq("course_id", bean.getCourseId());
        }
        return qw;
    }
}
